package com.zzept.error.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.IntStream;

/**
 * @description:
 * @author: szq
 * @create: 2020/03/13
 */
public class Exercise {

    private static ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();

    public static void main(String[] args) {
//        putIfAbsent();
        threadLocalRandom();
    }

    /**
     * computeIfAbsent和putIfAbsent区别是三点：
     * 1、当Key存在的时候，如果Value获取比较昂贵的话，putIfAbsent就白白浪费时间在获取这个昂贵的Value上（这个点特别注意）
     * 2、Key不存在的时候，putIfAbsent返回null，小心空指针，而computeIfAbsent返回计算后的值
     * 3、当Key不存在的时候，putIfAbsent允许put null进去，而computeIfAbsent不能，之后进行containsKey查询是有区别的（当然了，此条针对HashMap，ConcurrentHashMap不允许put null value进去）
     */
    private static void putIfAbsent(){
        ConcurrentHashMap<String, Long> concurrentHashMap = new ConcurrentHashMap<>();
        concurrentHashMap.putIfAbsent("a", 123L);
        concurrentHashMap.putIfAbsent("b", 345L);
        concurrentHashMap.putIfAbsent("a", 234L);
        concurrentHashMap.entrySet().stream().forEach(t->{
            System.out.println("key : " + t.getKey() + ", value : " + t.getValue());
        });
    }

    private static void threadLocalRandom(){
        List<Integer> list = new ArrayList<>();
        int loop  = 100;
        IntStream.rangeClosed(1, loop).parallel().forEach(t->list.add(threadLocalRandom.nextInt(loop)));
        list.stream().forEach(t->{
            System.out.println(t);
        });
    }
}
